package com.ruoyi.project.wx.api;


import cn.hutool.core.map.MapUtil;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bootdo.R;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.project.mall.domain.MallCompanyUserDO;
import com.ruoyi.project.mall.service.MallCompanyUserService;
import com.ruoyi.project.wx.dao.MemberCouponDao;
import com.ruoyi.project.wx.domain.*;
import com.ruoyi.project.wx.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * Created by HP on 2019/5/29.
 */
@Controller
@RequestMapping("/api/order")
public class ApiOrderController {

    @Autowired
    private OrderOrderService orderOrderService;
    @Autowired
    private MemberCartService memberCartService;
    @Autowired
    private MemberUserService memberUserService;
    @Autowired
    private GoodsProductService goodsProductService;
    @Autowired
    private MemberCouponDao memberCouponDao;
    @Autowired
    private GoodsSpikeService goodsSpikeService;
    @Autowired
    private GoodsNineService goodsNineService;
    @Autowired
    private GoodsBargainService goodsBargainService;
    @Autowired
    private GoodsSpikeTimeService goodsSpikeTimeService;
    @Autowired
    private MallCompanyUserService mallCompanyUserService;
    @Autowired
    private RedisCache redisCache;

    /**
     * 从缓存获取订单状态
     * @param paramMap
     * @return
     */
    @RequestMapping("/getOrderStatus")
    @ResponseBody
    public R getOrderStatus(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("payNum") || StringUtils.isBlank(paramMap.get("payNum").toString())

            ) {
                return R.error("参数错误");
            }


            Integer status = (Integer)redisCache.getCacheObject(MapUtil.getStr(paramMap, "payNum"));

            return R.ok().put("data",null ==status?1 : status);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("请重新提交");

        }
    }

    /**
     * 购物车确认订单
     * @param paramMap
     * @return
     */
    @RequestMapping("/confirmCartOrder")
    @ResponseBody
    public R confirmCartOrder(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString())
                    || !paramMap.containsKey("cartList") || StringUtils.isBlank(paramMap.get("cartList").toString())
            ) {
                return R.error("参数错误");
            }



            return orderOrderService.confirmCartOrder(paramMap);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("请重新提交");

        }
    }

    /***
     * 商品详情确认订单
     * @param paramMap
     * @return
     */
    @RequestMapping("/confirmGoodsOrder")
    @ResponseBody
    public R confirmGoodsOrder(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString())
                    || !paramMap.containsKey("goodsId") || StringUtils.isBlank(paramMap.get("goodsId").toString())
                    || !paramMap.containsKey("productId") || StringUtils.isBlank(paramMap.get("productId").toString())
                    || !paramMap.containsKey("total") || StringUtils.isBlank(paramMap.get("total").toString())
            ) {
                return R.error("参数错误");
            }

            String productId = paramMap.get("productId").toString();
            String id = paramMap.get("goodsId").toString();
            Integer total = Integer.valueOf(paramMap.get("total").toString());
            GoodsProductDO product = goodsProductService.get(productId);
            int stock = product.getStock();  //库存
            if (stock < total) {
                return R.error("商品库存不足，请选择其他商品");
            }
            int level = 0;
            String userId = paramMap.get("userId").toString();
            MemberUserDO user = memberUserService.get(userId);
            if(user.getLevel()==2){
                MallCompanyUserDO mallCompanyUserDO= mallCompanyUserService.getByUserId(userId);
                if(mallCompanyUserDO==null){
                    return R.error("企业信息有误");
                }else if(StringUtils.isBlank(mallCompanyUserDO.getName())){
                    return R.ok(0,"企业信息不全,请补全信息再下单").put("flag",0);
                }else if(mallCompanyUserDO.getLevel()==1){
                    level=1;
                }
            }

            int disabled = user.getDisabled();
            if (disabled == 1) {
                return R.error(2,"该账号已经冻结，请联系平台管理员");
            }
            //判断购买量和不为0
            if (total == 0) {
                return R.error("商品数量不能为0");
            }
            int min = product.getBuyMin();
            int max = product.getBuyMax();
            if (total < min) {
                return R.error("该商品最小购买量为"+min);
            } else if (total > max) {
                return R.error("该商品最大购买量为"+max);
            }


            return orderOrderService.confirmGoodsOrder(paramMap).put("level",level);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("请重新提交");

        }
    }

    /***
     *
     * @param paramMap 获取订单数
     * @return
     */
    @ResponseBody
    @RequestMapping("/getOrderNumByStatus")
    public R getOrderNumByStatus(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString()))
                    {
                return R.error("参数错误");
            }
            return orderOrderService.getOrderNumByStatus(paramMap);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("查询失败");
        }

    }

    /*
    * 购物车创建订单
    * cartList :  cartId
    * */
    @RequestMapping("/addCartOrder")
    @ResponseBody
    public R addCartOrder(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString())
                    || !paramMap.containsKey("cartList") || StringUtils.isBlank(paramMap.get("cartList").toString())
                    || !paramMap.containsKey("buyerMsg")
                    || !paramMap.containsKey("postFee") || StringUtils.isBlank(paramMap.get("postFee").toString())
                    || !paramMap.containsKey("addressId") || StringUtils.isBlank(paramMap.get("addressId").toString())
                    || !paramMap.containsKey("couponId")
                    || !paramMap.containsKey("type")
                    ) {
                return R.error("参数错误");
            }

            List<String> errorList = new ArrayList<String>();  //错误订单集合
            List<String> cartList = (List<String>)paramMap.get("cartList"); //商品集合
            for (String cartId : cartList) {
                MemberCartDO cart = memberCartService.get(cartId);
                String productId = cart.getProductId();
                int total = cart.getNum();
                if (total == 0) {
                    return R.error("商品数量不能为0");
                }
                //判断库存
                GoodsProductDO product = goodsProductService.get(productId);
                int stock = product.getStock();  //库存
                if (stock < total) {
                    errorList.add(cartId);
                    continue;
                }
            }
            if (errorList.size() != 0) {
                return R.error(1,"有订单库存不足，不能下单");
            }
            String userId = paramMap.get("userId").toString();
            MemberUserDO user = memberUserService.get(userId);
            int disabled = user.getDisabled();
            if (disabled == 1) {
                return R.error(2,"该账号已经冻结，请联系平台管理员");
            }

            //判断优惠券是否可用
            String couponId = paramMap.get("couponId").toString();
            MemberCouponDO memberCouponDO = memberCouponDao.get(couponId);
            if (memberCouponDO != null) {
                int status = memberCouponDO.getStatus();
                if (status != 0) {
                    return R.error("该优惠券不能使用");
                }
            }
            return orderOrderService.addCartOrder(paramMap);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("请重新提交");

        }
    }

    /*
    * 商品详情创建订单（普通、9.9、秒杀商品）
    * type  0：普通商品，1：秒杀商品，2:9.9商品 5:审核订单
    * id：type为0时传商品id，type为1时传秒杀id，type为2时传9.9专区id
    * */
    @RequestMapping("/addGoodsOrder")
    @ResponseBody
    public R addGoodsOrder(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString())
                    || !paramMap.containsKey("id") || StringUtils.isBlank(paramMap.get("id").toString())
                    || !paramMap.containsKey("productId") || StringUtils.isBlank(paramMap.get("productId").toString())
                    || !paramMap.containsKey("total") || StringUtils.isBlank(paramMap.get("total").toString())
                    || !paramMap.containsKey("buyerMsg")
                    || !paramMap.containsKey("postFee") || StringUtils.isBlank(paramMap.get("postFee").toString())
                    || !paramMap.containsKey("addressId") || StringUtils.isBlank(paramMap.get("addressId").toString())
                    || !paramMap.containsKey("type") || StringUtils.isBlank(paramMap.get("type").toString())
                    || !paramMap.containsKey("couponId")
                    ) {
                return R.error("参数错误");
            }
            Integer type = Integer.valueOf(paramMap.get("type").toString());
            String productId = paramMap.get("productId").toString();
            String id = paramMap.get("id").toString();
            Integer total = Integer.valueOf(paramMap.get("total").toString());
            GoodsProductDO product = goodsProductService.get(productId);
            int stock = product.getStock();  //库存
            if (stock < total) {
                return R.error("商品库存不足，请选择其他商品");
            }
            if (type == 1) {  //秒杀商品
                GoodsSpikeDO spikeDO = goodsSpikeService.get(id);
                int spikeNum = spikeDO.getStock();
                if (spikeNum < total) {
                    return R.error("该秒杀商品已卖完，请选择其他商品");
                }
                //判断秒杀时间
                String timeId = spikeDO.getTimeId();
                GoodsSpikeTimeDO goodsSpikeTimeDO = goodsSpikeTimeService.get(timeId);
                Date startAt = goodsSpikeTimeDO.getStartAt();
                Date endAt = goodsSpikeTimeDO.getEndAt();
                Date now = new Date();
                if (startAt.after(now)) {
                    return R.error("该商品秒杀还没开始");
                }
                if (!endAt.after(now)) {
                    return R.error("该商品秒杀已结束");
                }

            } else if (type == 2) {   //9.9商品
                int nineNum = goodsNineService.get(id).getStock();
                if (nineNum < total) {
                    return R.error("该专区商品已卖完，请选择其他商品");
                }
            }
            String userId = paramMap.get("userId").toString();
            MemberUserDO user = memberUserService.get(userId);
            int disabled = user.getDisabled();
            if (disabled == 1) {
                return R.error(2,"该账号已经冻结，请联系平台管理员");
            }
            //判断购买量和不为0
            if (total == 0) {
                return R.error("商品数量不能为0");
            }
            int min = product.getBuyMin();
            int max = product.getBuyMax();
            if (total < min) {
                return R.error("该商品最小购买量为"+min);
            } else if (total > max) {
                return R.error("该商品最大购买量为"+max);
            }

            //判断优惠券是否可用
            String couponId = paramMap.get("couponId").toString();
            MemberCouponDO memberCouponDO = memberCouponDao.get(couponId);
            if (memberCouponDO != null) {
                int status = memberCouponDO.getStatus();
                if (status != 0) {
                    return R.error("该优惠券不能使用");
                }
            }
            return orderOrderService.addGoodsOrder(paramMap);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("请重新提交");

        }
    }

    /*
    * 创建砍价订单
    * total 固定为 1
    * */
    @RequestMapping("/addBargainOrder")
    @ResponseBody
    public R addBargainOrder(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString())
                    || !paramMap.containsKey("bargainId") || StringUtils.isBlank(paramMap.get("bargainId").toString())
                    || !paramMap.containsKey("productId") || StringUtils.isBlank(paramMap.get("productId").toString())
                    || !paramMap.containsKey("total") || StringUtils.isBlank(paramMap.get("total").toString())
                    || !paramMap.containsKey("buyerMsg")
                    || !paramMap.containsKey("postFee") || StringUtils.isBlank(paramMap.get("postFee").toString())
                    || !paramMap.containsKey("addressId") || StringUtils.isBlank(paramMap.get("addressId").toString())
                    || !paramMap.containsKey("couponId")
                    ) {
                return R.error("参数错误");
            }
            String productId = paramMap.get("productId").toString();
            String bargainId = paramMap.get("bargainId").toString();
            Integer total = Integer.valueOf(paramMap.get("total").toString());
            if (total != 1) {
                return R.error("该商品只能买一件");
            }
            GoodsProductDO product = goodsProductService.get(productId);
            int stock = product.getStock();  //库存
            if (stock < total) {
                return R.error("商品库存不足，请选择其他商品");
            }
            int bargainNum = goodsBargainService.get(bargainId).getStock();
            if (bargainNum < total) {
                return R.error("该专区商品已卖完，请选择其他商品");
            }

            String userId = paramMap.get("userId").toString();
            MemberUserDO user = memberUserService.get(userId);
            int disabled = user.getDisabled();
            if (disabled == 1) {
                return R.error(2,"该账号已经冻结，请联系平台管理员");
            }
            //判断优惠券是否可用
            String couponId = paramMap.get("couponId").toString();
            MemberCouponDO memberCouponDO = memberCouponDao.get(couponId);
            if (memberCouponDO != null) {
                int status = memberCouponDO.getStatus();
                if (status != 0) {
                    return R.error("该优惠券不能使用");
                }
            }
            return orderOrderService.addBargainGoodsOrder(paramMap);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("请重新提交");

        }
    }


    /*
    * 查看个人订单列表
    * type 1:待支付， 2：代发货，3：待收货，4：待评价，5：问题订单，0：全部
    * */
    @ResponseBody
    @RequestMapping("/getOrderList")
    public R getOrderList(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString())
                    || !paramMap.containsKey("type") || StringUtils.isBlank(paramMap.get("type").toString())
                    || !paramMap.containsKey("name")
                    || !paramMap.containsKey("orderAt")

            ) {
                return R.error("参数错误");
            }
            PageInfo<Map<String,Object>> list = orderOrderService.getOrderListByStatus(paramMap);
            return R.ok().put("data", list);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("查询失败");
        }

    }

    /*
    * 取消/收货 订单
    * type ，8：订单取消，7：收货
    * */
    @ResponseBody
    @RequestMapping("/setStatusOrder")
    public R setStatusOrder(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString())
                    || !paramMap.containsKey("type") || StringUtils.isBlank(paramMap.get("type").toString())
                    || !paramMap.containsKey("orderId") || StringUtils.isBlank(paramMap.get("orderId").toString())
                    ) {
                return R.error("参数错误");
            }
            if(orderOrderService.setStatusOrder(paramMap) == 0) {
                return R.ok();
            }
            return R.error();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("操作失败");
        }
    }

    /*
    * 评价订单
    * comentList   start:星级，content:评价内容, detailId：分订单id，imgurls
    * */
    @ResponseBody
    @RequestMapping("/setComent")
    public R setComent(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString())
                    || !paramMap.containsKey("comentList") || StringUtils.isBlank(paramMap.get("comentList").toString())
                    || !paramMap.containsKey("orderId") || StringUtils.isBlank(paramMap.get("orderId").toString())
                    ) {
                return R.error("参数错误");
            }
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("userId",paramMap.get("userId"));
            map.put("id",paramMap.get("orderId"));
            List<OrderOrderDO> orderList = orderOrderService.list(map);
            if (orderList.size() == 0) {
                return R.error("订单异常");
            }
            OrderOrderDO orderOrderDO = orderList.get(0);
            if (orderOrderDO.getComent() == 1) {
                return R.error("订单已评价");
            }
            if (orderOrderDO.getStatus() != 7) {
                return R.error("该订单暂不能评价");
            }

            int a = orderOrderService.setComent(paramMap);
            if(a == 0) {
                return R.ok();
            } else if (a == 1) {
                return R.error("评价内容不能为空");
            }
            return R.error();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("操作失败");
        }
    }

    /*
    * 订单详情(普通、秒杀、9.9)
    * */
    @ResponseBody
    @RequestMapping("/getOrderById")
    public R getOrderById(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString())
                    || !paramMap.containsKey("orderId") || StringUtils.isBlank(paramMap.get("orderId").toString())
                    ) {
                return R.error("参数错误");
            }
            Map<String,Object> map = orderOrderService.getOrderById(paramMap);
            return R.ok().put("data", map);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("操作失败");
        }
    }

    /*
    * 订单详情(砍价)
    * */
    @ResponseBody
    @RequestMapping("/getKOrderById")
    public R getKOrderById(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString())
                    || !paramMap.containsKey("orderId") || StringUtils.isBlank(paramMap.get("orderId").toString())
                    ) {
                return R.error("参数错误");
            }
            Map<String,Object> map = orderOrderService.getKOrderById(paramMap);
            return R.ok().put("data",map);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("操作失败");
        }
    }

    /*
    * 申请退货
    * */
    @ResponseBody
    @RequestMapping("/backGood")
    public R backGood(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString())
                    || !paramMap.containsKey("id") || StringUtils.isBlank(paramMap.get("id").toString())
                    /*|| !paramMap.containsKey("expressName") || StringUtils.isBlank(paramMap.get("expressName").toString())
                    || !paramMap.containsKey("expressCode") || StringUtils.isBlank(paramMap.get("expressCode").toString())*/
                    || !paramMap.containsKey("reason") || StringUtils.isBlank(paramMap.get("reason").toString())
                    ) {
                return R.error("参数错误");
            }
            paramMap.put("status", "4");   //待收货
            List<OrderOrderDO> orderList = orderOrderService.list(paramMap);
            if (orderList.size() == 0) {
                return R.error("订单错误");
            }
            if (orderOrderService.backGood(paramMap) == 1) {
                return R.ok();
            } else {
                return R.error();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("失败");
        }
    }

    /*
    * 删除订单
    * */
    @ResponseBody
    @RequestMapping("/removeOrder")
    public R removeOrder(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString())
                    || !paramMap.containsKey("orderIdList") || StringUtils.isBlank(paramMap.get("orderIdList").toString())
                    ) {
                return R.error("参数错误");
            }
            return orderOrderService.removeOrder(paramMap);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("失败");
        }
    }



}
